package com.company.dp;


import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @author jrue
 * @description https://leetcode-cn.com/problems/minimum-path-sum/
 * @date 2019/11/19 8:14
 * 给定一个包含非负整数的 m x n 网格，请找出一条从左上角到右下角的路径，使得路径上的数字总和为最小。
 *
 * 说明：每次只能向下或者向右移动一步。
 */
public class MinimumPathSum {


    public static void main(String[] args) {
        System.out.println(minPathSum(new int[][]{
                {1, 3, 1},
                {1, 5, 1},
                {4, 2, 1}
        }));
    }

    public static int minPathSum(int[][] grid) {
        int[][] dp = new int[grid.length][grid[0].length];

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (i == 0 && j == 0) dp[0][0] = grid[0][0];
                else if (i -1 < 0) dp[i][j] = grid[i][j] + dp[i][j - 1];
                else if (j - 1 < 0) dp[i][j] = grid[i][j] + dp[i - 1][j];
                else {
                    dp[i][j] = Math.min(dp[i - 1][j] + grid[i][j],dp[i][j - 1] + grid[i][j]);
                }
            }
        }

        return dp[grid.length - 1][grid[0].length - 1];
    }

}
